package com.suntoon.framework.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.suntoon.framework.annotation.SkipLogin;
import com.suntoon.framework.common.Constants;
import com.suntoon.framework.common.response.ResultBO;
import com.suntoon.framework.util.JwtTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @Author: LEAVES
 * @Version 1.0
 * @Date: 2021年06月21日 17时28分33秒
 * @Description: 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private RedisTemplate redisTemplate;

    //访问接口之前执行验证登陆状态
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果不是映射到方法,放行
        if (!(handler instanceof HandlerMethod) || (Constants.TOKEN_ACTIVITY != null && !Constants.TOKEN_ACTIVITY)) {
            return true;
        }
        SkipLogin skipLogin = ((HandlerMethod) handler).getMethodAnnotation(SkipLogin.class);
        if (null == skipLogin) {
            skipLogin = ((HandlerMethod) handler).getMethod().getDeclaringClass().getAnnotation(SkipLogin.class);
        }
        // 有跳过登录验证注解,放行
        if (null != skipLogin) {
            return true;
        }
        //从header中得到token
        String token = request.getHeader(Constants.AUTHORIZATION);
        //验证token
        if (StringUtils.isNotBlank(token)) {
            token = token.replace("Bearer ", "");
            String username = JwtTokenUtil.getUsername(token);
            if (JwtTokenUtil.verify(token, username)) {
                if (redisTemplate.hasKey(username)) {
                    redisTemplate.expire(username, Constants.TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);
                    return true;
                }
            }
        }
//        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        JSONObject object = new JSONObject();
        ResultBO resultBO = new ResultBO();
        resultBO.setCode(401);
        resultBO.setMsg("请登录");
        object.put("result",resultBO);
        String json = object.toString();
        writeReturnJson(response, json);
        return false;
    }


    /**
     * 返回的json值
     *
     * @param response
     * @param json
     * @throws Exception
     */
    private void writeReturnJson(HttpServletResponse response, String json) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);
        } catch (IOException e) {
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
